package com.matt.repository.impl;

import com.matt.domain.Attachment;
import com.matt.foundation.query.AttachmentQuery;
import com.matt.repository.base.AttachmentNativeRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ***************************
 * Created by Ron
 * from com.matt
 * on 2018/6/26 0026.
 * ***************************
 */
@Service
@Transactional
public class AttachmentNativeRepositoryImpl extends BaseNativeSqlRepository implements AttachmentNativeRepository{


    @Override
    public List<Attachment> findPage(AttachmentQuery attachmentQuery) {
       String querySql=String.format("select at.id,at.name,at.type,at.staffId,at.staffName,at.leadsId,at.contractId,at.created,at.deleted,at.attachmentUrl from attachment as at where true");

       if (StringUtils.isNotBlank(attachmentQuery.getLeadsId()))
           querySql +=String.format(" and at.leadsId='%s'",attachmentQuery.getLeadsId());
       if(StringUtils.isNotBlank(attachmentQuery.getContractId()))
           querySql +=String.format(" and at.contractId='%s'",attachmentQuery.getContractId());
        if(StringUtils.isNotBlank(attachmentQuery.getClienteleId()))
            querySql +=String.format(" and at.clienteleId='%s'",attachmentQuery.getClienteleId());

        querySql +=String.format(" order by at.created desc");
        querySql +=String.format(" limit %s,%s ",attachmentQuery.getPageNum() * attachmentQuery.getPageSize(),attachmentQuery.getPageSize());
        List<Attachment> objectList=sqlObjectList(querySql,Attachment.class);
        return objectList;
    }

    @Override
    public Long count(AttachmentQuery attachmentQuery) {
        String querySql=String.format("select count(at.id) from attachment as at where true");
        if (StringUtils.isNotBlank(attachmentQuery.getLeadsId()))
            querySql +=String.format(" and at.leadsId='%s'",attachmentQuery.getLeadsId());
        if(StringUtils.isNotBlank(attachmentQuery.getContractId()))
            querySql +=String.format(" and at.contractId='%s'",attachmentQuery.getContractId());
        if(StringUtils.isNotBlank(attachmentQuery.getClienteleId()))
            querySql +=String.format(" and at.clienteleId='%s'",attachmentQuery.getClienteleId());
        List objectArrayList = sqlSingleList(querySql);
        return  Long.valueOf(objectArrayList.get(0).toString());
    }
}
